<?php

namespace App\Http\Controllers;

use App\Contracts\Construct;
use App\Imports\Common;
use App\Models\Contract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    use Responser;
    use \App\Traits\Debug;


    protected $model;


    // 查看详情公共方法
    public function show($id)
    {
        if (!($this->model instanceof Model)) {
            throw new \Exception('请先使用__construct()方法，实例化$model');
        }
        $show = $this->model::find($id);

        if (!$show) {
            return $this->resError('不存在');
        }
        return $this->resSuccess('', $show);
    }

    //每页显示条数
    protected $per_page = 20;

    public function getPerPage(Request $req)
    {
        return  $req->per_page ? intval($req->per_page) : $this->per_page;
    }

    static public function resSuccess($msg='操作成功', $data=[]) : array
    {
        return [
            'status' => 1,
            'message' => $msg,
            'dat' => $data,
        ];
    }

    public function resError($msg='操作失败！')
    {
        return [
            'status' => 0,
            'message' => $msg,
        ];
    }

    // 查询id修改对象是否存在
    public function find(Model $model, $pk, $msg='信息不存在!')
    {
        if ($obj = $model::find($pk)){
            return $obj;
        } else {
            return self::debug($msg);
        }
    }


    public function delete(Model $model, $id)
    {

        try{
            $builder = $model->newQuery();
            $model = $builder->findOrFail($id);
            $model->delete();

            return true;
        }catch (\Exception $e) {
            return self::debug($e->getMessage());
        }


    }

    // 导出Excel
    public function resExcel($dat, $filename='test.xlsx')
    {
        return \Excel::download(
            new \App\Exports\Common($dat, $filename),
            $filename
        );
    }


    use \Maatwebsite\Excel\Concerns\Importable;
    /**
     * 初始化上传导入的Excel数据 并使用header的字段作为key
     * @param $req->file('file') $file 上传的文件
     * @param array $header excel表头字段 如： ['name','no','email', ....]
     * @param null|int $sheet=all2 则输出所有sheet，否则返回指定的sheet, 从0开始
     * @return array
     * */
    public function reqExcel ($file, $header, $sheet=0)
    {

        $excelData = \Excel::toArray(new Common($header), $file);
        if (!empty($excelData) && is_array($excelData)) {
            if ($sheet === 'all') {
                return $excelData;
            } else {
                return $excelData[$sheet];
            }

        } else {
            return false;
        }




        /*try {
            $excel = self::excel();
            return $excel::import($file, $line, $page);
        } catch (\Exception $e) {
            return self::debug($e->getMessage());
        }*/
        $excel = $this->toArray($file);
        foreach ($excel as $i=>&$sheet) {

            if (isset($page) and $page!=$i) {
                continue;
            }
            $key = array_shift($sheet);
            foreach ($sheet as $i=>&$row) {
                if ($i<$line) {
                    unset ($sheet[$i]);
                    continue;
                }
                $row = array_combine($key, $row);
                foreach ($row as $k=>&$v) {
                    $v = trim($v);
                }
            }

            $sheet = array_values($sheet);
        }
        return isset($page) ? @$excel[$page] : $excel;

    }


    /** 下载文件
     * @param $file string 文件名(包括文件扩展名)
     * @return string
     */
    public function downFile($file)
    {
        return config('admin.app_url').'/files/'.$file;

    }

}
